package org.lanyu.springainovel.common.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.lanyu.springainovel.common.vo.ArticleVO;
import org.lanyu.springainovel.common.vo.RestVO;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "后端代理", description = "后端代理")
@RestController
@RequestMapping
public class ProxyController {
    public ProxyController() { super(); }

    @GetMapping("/proxy")
    public void proxy(@RequestParam String url, HttpServletResponse response) throws IOException {
        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            conn.setRequestProperty("Referer", "https://www.csdn.net/");
            conn.setRequestProperty("Origin", "https://www.csdn.net/");
            String contentType = conn.getContentType();
            if (contentType != null) {
                response.setContentType(contentType);
            }
            try (InputStream in = conn.getInputStream(); OutputStream out = response.getOutputStream()) {
                byte[] buf = new byte[8192];
                int len;
                while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
            }
        } catch (Exception e) {
            // 返回自定义错误页�?
            response.setStatus(200); // 让前端能拿到内容
            response.setContentType("text/html; charset=utf-8");
            String msg = "<div style='color:red;padding:2em;text-align:center;'>"
                    + "代理抓取失败" + e.getClass().getSimpleName() + "<br/>"
                    + (e.getMessage() != null ? e.getMessage() : "")
                    + "</div>";
            response.getWriter().write(msg);
        }
    }

    @GetMapping("/articles")
    public RestVO<List<ArticleVO>> getArticles() {
        List<ArticleVO> articles = new ArrayList<>();
        try {
            // 使用JSoup爬取CSDN博客文章列表
            Document doc = Jsoup.connect("https://blog.csdn.net/u012796085/category_12996489.html")
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .referrer("https://www.csdn.net/")
                    .timeout(10000)
                    .get();

            // 查找所有文章链�?
            Elements articleLinks = doc.select("#column > ul > li > a");
            
            for (Element link : articleLinks) {
                try {
                    // 获取文章链接
                    String url = link.attr("href");
                    if (url.isEmpty() || !url.contains("/article/details/")) {
                        continue; // 跳过非文章链�?
                    }
                    
                    // 获取文章标题
                    Element titleElement = link.select("div.column_article_title > h2").first();
                    if (titleElement == null) {
                        continue; // 跳过没有标题的文�?
                    }
                    
                    String title = titleElement.text().trim();
                    if (title.isEmpty()) {
                        continue; // 跳过空标�?
                    }
                    // 只保�?�?及之前的部分
                    int endIdx = title.indexOf(",");
                    if (endIdx != -1) {
                        title = title.substring(endIdx+1);
                    }
                    
                    // 确保URL是完整的
                    if (!url.startsWith("http")) {
                        url = "https://blog.csdn.net" + url;
                    }
                    
                    articles.add(new ArticleVO(title, url));
                } catch (Exception e) {
                    // 单个文章解析失败，继续处理下一�?
                    System.err.println("解析文章失败: " + e.getMessage());
                }
            }
            
            return RestVO.success(articles);
        } catch (Exception e) {
            System.err.println("爬取文章列表失败: " + e.getMessage());
            e.printStackTrace();
            return RestVO.fail("获取文章列表失败: " + e.getMessage());
        }
    }
}
